#coding:utf-8

import SocketServer
import json
import threading
import traceback
import bottle

# 需要改为实际的路径
static_root = '/home/xiaolu/projects/shumeipai/static'
host = "0.0.0.0"
sensor_port = 5000
web_port = 8080

# 用来保存从sensor发来的数据
data_stored = []

# 设置缓存数据的个数
data_stored_length = 5


class SensorServer(SocketServer.StreamRequestHandler):
    # SensorSever继承与SocketServer.StreamRequestHandler,它是一个SocketSever

    def handle(self):
        # 一次性接收最大1024字节的数据
        data = self.request.recv(1024)

        sensor_list = []
        n = 0
        try:
            # 解析3个数据
            for i in xrange(3):
                # ord就是取这个字节值
                phy_addr = ord(data[n])
                n += 1
                logic_addr = ord(data[n])
                n += 1
                status = ord(data[n])
                n += 1
                temperature = ord(data[n]) / 2
                n += 1

                # 电压没有算,现在直接把字节赋给它了,需要进一步计算
                voltage = data[n:n + 2]
                n += 2

                # 不知道这个是什么
                rssi = data[n:n + 2]
                n += 2

                # 将封装成一个字典,便于读取
                sensor = {
                    "phy_addr": phy_addr,
                    "logic_addr": logic_addr,
                    "status": status,
                    "temperature": temperature,
                    "voltage": voltage,
                    "rssi": rssi,
                }
                sensor_list.append(sensor)

            # 如果发现数据个数大于指定位数,就需要把第一个pop出来
            if len(data_stored) >= data_stored_length:
                data_stored.pop(0)

            # 将数据存入data_stored
            data_stored.append(sensor_list)
            print data_stored
        except:
            traceback.print_exc()


def sensor_listener():
    server = SocketServer.ThreadingTCPServer((host, sensor_port), SensorServer)
    server.serve_forever()

@bottle.route('/', method='GET')
def index():
    # 这是主界面,路径是'/',方法为GET,返回index.html
    return bottle.static_file('index.html', static_root)

@bottle.route('/static/<filename:path>', method='GET')
def static(filename):
    # 返回静态文件
    return bottle.static_file(filename, static_root)

@bottle.route('/data', method='GET')
def send_data():
    # 按json格式发送数据,供js解析
    return bottle.HTTPResponse(json.dumps(data_stored))

def web_listener():
    # 开启bottle服务
    bottle.run(host=host, port=web_port)

if __name__ == "__main__":
    # 开启两个线程启动2个服务
    sensor_thread = threading.Thread(target=sensor_listener)
    sensor_thread.start()
    web_thread = threading.Thread(target=web_listener)
    web_thread.start()
    sensor_thread.join()
    web_thread.join()
